
package com.code.entity.generator;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.code.constant.SqlConstant;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JobGenerator {


    static String PATH = "";
    static String PREFIX_DIR = File.separator + "script" + File.separator;

    static String PATH_JOB_EXCEL = "t_job.xls";

    static String VERSION_FILE_PATH = "data/script/seperatebycustomer/";

    static String INSERT_JOB = "INSERT ignore INTO `t_job`(`id`, `job_name`, `job_group`, `job_state`, `start_time`," +
            " `day_of_start`, `day_of_end`, `end_time`, `interval`, `interval_type`, `repeat_count`," +
            " `job_node`, `folder_path`, `file_prefix`, `last_file`, `bus_date`, `remark`) " +
            "VALUES (";
    static String INSERT_END = ");\n";



    public static void main(String[] args) throws IOException {
        //生成单独字典脚本
        generate();
    }


    private static String getTruncateSql(String tableName) {
        StringBuilder sb = new StringBuilder();
        sb.append(" -- truncate table ")
                .append(tableName)
                .append(";\n");
        return sb.toString();
    }

    private static Map<String, String> getCustomerJob(List<Job> jobs) {
        Map<String, String> fileSqlMap = new HashMap<>();
        Map<String, String> versions = getAllVersions(jobs);
        versions.forEach((k, v) -> {
            String version = k;
            String fileName = "10.job_" + version;

            StringBuilder sb = new StringBuilder();
            sb.append(getTruncateSql("t_job"));
            jobs.forEach(job -> {
                if (StringUtils.isNotBlank(job.getVersion()) && job.getVersion().indexOf(k) > -1) {
                    sb.append(INSERT_JOB);
                    sb.append("'").append(job.getId()).append("'").append(",");
                    sb.append("'").append(job.getJobName()).append("'").append(",");
                    sb.append("'").append(job.getJobGroup()).append("'").append(",");
                    sb.append("'").append(job.getJobState()).append("'").append(",");
                    sb.append("'").append(job.getStartTime()).append("'").append(",");
                    sb.append("'").append(job.getDayOfStart()).append("'").append(",");
                    sb.append("'").append(job.getDayOfEnd()).append("'").append(",");
                    sb.append("'").append(job.getEndTime()).append("'").append(",");
                    sb.append("'").append(job.getInterval()).append("'").append(",");
                    sb.append("'").append(job.getIntervalType()).append("'").append(",");
                    sb.append("'").append(job.getRepeatCount()).append("'").append(",");
                    sb.append("'").append(job.getJobNode()).append("'").append(",");
                    sb.append("'").append(job.getFolderPath()).append("'").append(",");
                    sb.append("'").append(job.getFilePrefix()).append("'").append(",");
                    sb.append("'").append(job.getLastFile()).append("'").append(",");
                    sb.append("'").append(job.getBusDate()).append("'").append(",");
                    sb.append("'").append(job.getRemark()).append("'");
                    sb.append(INSERT_END);
                }
            });
            fileSqlMap.put(fileName, sb.toString().replaceAll("'null'", "NULL")
                    .replaceAll("'NULL'", "NULL"));
        });


        return fileSqlMap;
    }

    private static Map<String, String> getAllVersions(List<Job> jobs) {
        Map<String, String> map = new HashMap<>();
        jobs.forEach(job -> {
            String version = job.getVersion();
            if (StringUtils.isNotBlank(version)) {
                String[] vs = version.split("-");
                for (int i = 0; i < vs.length; i++) {
                    if (!map.containsKey(vs[i])) {
                        map.put(vs[i], "1");
                    }
                }
            }
        });
        return map;
    }

    public static void generate() {
        //先获取文件绝对路径
        getAbsolutePath();


        String dir = PATH + PATH_JOB_EXCEL;
        File file = new File(dir);
        ImportParams params = new ImportParams();
        List<Job> jobList = ExcelImportUtil.importExcel(file, Job.class, params);
        Map<String, String> customerSql = getCustomerJob(jobList);

        customerSql.forEach((k, v) -> {
            File file1 = new File(VERSION_FILE_PATH + k + ".sql");
            if (file1.exists()) {
                file1.delete();
            }
            file1 = new File(VERSION_FILE_PATH + k + ".sql");
            try {
                file1.createNewFile();
                PrintWriter pfp1 = new PrintWriter(file1, "UTF-8");
                pfp1.print(SqlConstant.mysqlUseDb);
                pfp1.print(v);
                pfp1.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("单拎job" + k + "{}完成");
        });
        System.out.println("生成单拎job完成，共：" + customerSql.size() + "个单独脚本");


    }

    private static void getAbsolutePath() {
        //打包时路径
        PATH = System.getProperty("user.dir");
        System.out.println("=======当前目录 " + PATH);
        PATH = PATH.substring(0, PATH.lastIndexOf(File.separator)) + PREFIX_DIR;
        System.out.println("=======PATH:" + PATH);
        VERSION_FILE_PATH = PATH + "seperatebycustomer" + File.separator;
        System.out.println("=======VERSION_FILE_PATH:" + VERSION_FILE_PATH);
    }


    static HashMap filelist = new HashMap();

}
